import { cloneDeep } from 'lodash';
import { BasicTableProps, Recordable } from '../types';
import { ComputedRef, ref, watch, computed, unref } from 'vue';

export interface IFromItem {}
function getSearchFormData(data: Recordable[]) {
  return data.reduce((pre, current) => {
    if (typeof current.value === 'object') {
      pre[current.attrs.prop] = cloneDeep(current.value);
    } else {
      pre[current.attrs.prop] = current.value;
    }
    return pre;
  }, {});
}
export function useSearchForm(props: ComputedRef<BasicTableProps>) {
  const formData = ref<Recordable>({});
  const formItems = ref<any[]>([]);
  const showSearchFrom = ref(false);

  watch(
    () => props.value.searchFromItems,
    (val) => {
      if (val) {
        setFormItems(cloneDeep(val));
      } else {
        showSearchFrom.value = false;
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const getShowSearchButton = computed(() => {
    return unref(formItems).length > 0;
  });

  const getSearchParams = computed(() => {
    return cloneDeep(unref(formData));
  });

  function setFormItems(value: any) {
    formItems.value = cloneDeep(value);
    formData.value = getSearchFormData(value);
    showSearchFrom.value = formItems.value.length > 0;
  }
  function setFormData(value: any) {
    formData.value = {
      ...formData.value,
      ...value,
    };
  }

  // 重置
  function reset() {
    formData.value = getSearchFormData(formItems.value ?? []);
  }

  function getSearchInfo() {
    return cloneDeep(unref(formData));
  }

  return {
    showSearchFrom,
    formData,
    formItems,
    getSearchParams,
    getShowSearchButton,
    getSearchInfo,
    reset,
    setFormItems,
    setFormData,
  };
}
